package com.accessibleworlds.blind;

import java.util.ArrayList;

import com.accessibleworlds.util.Connections;
import com.accessibleworlds.util.SharedVariables;
import com.accessibleworlds.util.TextToSpeeches;
import com.accessibleworlds.util.TextToSpeechesGoogle;
import com.accessibleworlds.util.TextToSpeechesPico;
import com.accessibleworlds.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;

/**
 * The default blind user gateway page.
 * @author Ayberk Özgür
 *
 */
public class BlindUserGatewayPage extends Activity implements MultitouchGestureListener{
	private TextToSpeeches tts = null;
	private boolean exitRequested = false;
	private boolean ttsReady = false;
	private Thread connectionThread;
	private ArrayList<BlindUserMenuItem> spokenMenu = null;
	private int currentItem = 0;
	private int numberOfItems = 3;
	private String username = null;
	private String password = null;

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.blinduserpage);

		progressDialog = new ProgressDialog(this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);

		//Populate the spoken menu
		spokenMenu = new ArrayList<BlindUserMenuItem>();
		Intent intent;
		intent = new Intent(this,BlindUserSpeechToTextActivity.class);
		intent.putExtra("item_to_get", "user name");
		intent.putExtra("language", "en-US");
		spokenMenu.add(new BlindUserMenuItem(this,getResources().getStringArray(R.array.blind_gateway_items)[0],intent,true));
		intent = new Intent(this,BlindUserSpeechToTextActivity.class);
		intent.putExtra("item_to_get", "password");
		intent.putExtra("language", "en-US");
		spokenMenu.add(new BlindUserMenuItem(this,getResources().getStringArray(R.array.blind_gateway_items)[1],intent,true));
		spokenMenu.add(new BlindUserMenuItem(this,getResources().getStringArray(R.array.blind_gateway_items)[2],null,false));

		connectionThread = new Thread(new Runnable() {
			public void run() {
				connection();
			}
		});
		connectionThread.start();
	}

	@Override
	public void onBackPressed() {
	}

	private void connection() {
		if("0".equalsIgnoreCase(getResources().getStringArray(R.array.languageValues)[SharedVariables.currentLanguage]))
			tts = new TextToSpeechesPico();
		else
			tts = new TextToSpeechesGoogle();
		tts.speak(BlindUserGatewayPage.this, getResources().getString(R.string.blind_gateway) + "Current item: " + spokenMenu.get(currentItem).getSpokenName());
		ttsReady = true;
	}

	public void multitouchMotionEvent(int numberOfFingers, GestureType gestureType) {
		if(ttsReady){
			tts.stopSpeaking();
			switch(gestureType){
			case DOWN:
				exitRequested = false;
				currentItem = (currentItem + 1) % numberOfItems;
				tts.speak(BlindUserGatewayPage.this, spokenMenu.get(currentItem).getSpokenName());
				break;
			case UP:
				exitRequested = false;
				currentItem--;
				if(currentItem < 0)
					currentItem = numberOfItems - 1;
				tts.speak(BlindUserGatewayPage.this, spokenMenu.get(currentItem).getSpokenName());
				break;
			case LEFT:
				if(exitRequested)
					finish();
				else{
					exitRequested = true;
					tts.speak(BlindUserGatewayPage.this, getResources().getString(R.string.blind_exit_requested));
				}
				break;
			case RIGHT:
				exitRequested = false;
				if(currentItem == 2){
					if(username == null || username.equals(""))
						tts.speak(BlindUserGatewayPage.this, "Please enter your user name. ");
					else if(password == null || password.equals(""))
						tts.speak(BlindUserGatewayPage.this, "Please enter your password. ");
					else{
						tts.speak(BlindUserGatewayPage.this, "Logging you in...");
						(new LoginTask()).execute(new String[]{username,password});
					}
				}
				else
					spokenMenu.get(currentItem).selectItem();
				break;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String itemToGet = data.getExtras().getString("item_to_get");
		if(itemToGet.equals("user name")){
			username = data.getExtras().getString("result");
			tts.speak(BlindUserGatewayPage.this, "User name was set successfully. Current item: " + spokenMenu.get(currentItem).getSpokenName());
		}
		else if(itemToGet.equals("password")){
			password = data.getExtras().getString("result");
			tts.speak(BlindUserGatewayPage.this, "Password was set successfully. Current item: " + spokenMenu.get(currentItem).getSpokenName());
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * This is for checking variables without using views.
	 * 
	 * @param emailString : This is email of the user.
	 * @param passwordString : This is password of the user.
	 * @return true or false
	 */
	private boolean checkVariablesBackground(String emailString, String passwordString) {
		boolean check = true;

		if(!(emailString.length()>0 && emailString.length()<=100)) {
			check = false;
		}

		if(!(passwordString.length()>0 && passwordString.length()<=255)) {
			check = false;
		}

		return check;
	}

	public class LoginTask extends AsyncTask<String, Integer, String>{
		private String [] takenData = null;
		private String emailString = "";
		private String passwordString = "";

		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			emailString = params[0];
			passwordString = params[1];

			if(Connections.serviceStatus()) {
				if(checkVariablesBackground(emailString,passwordString)) {
					try {
						String url = Connections.URI+Connections.login;
						String [] parameters = {"accessCode","email","password"};
						String [] paramaterValues = {SharedVariables.accessCode,emailString,passwordString};

						takenData = Connections.connection(url,parameters,paramaterValues);

						if(takenData.length==0) {
							publishProgress(1);
						}
						else if("Not Exist!!!".equalsIgnoreCase(takenData[1])) {
							publishProgress(1);
							return "Not Exist!!!";
						}
						else if("Not Activated!!!".equalsIgnoreCase(takenData[1])) {
							publishProgress(2);
							return "Not Activated!!!";
						}
						else if("OK".equalsIgnoreCase(takenData[0])) {
							publishProgress(3);
							return "OK";
						}
						else {
							publishProgress(4);
						}
					} catch (Exception e) {
						publishProgress(1);
					}
				}
				else {
					publishProgress(1);
				}
			}
			else {
				publishProgress(0);
			}
			return "Fail";
		}

		protected void onProgressUpdate(Integer... progress) {
			if(progress[0] == 0) {
				progressDialog.dismiss();
				tts.speak(BlindUserGatewayPage.this, "Connection problem. Please try again. Current item: " + spokenMenu.get(currentItem).getSpokenName());
			}
			else if(progress[0] == 1) {
				progressDialog.dismiss();
				tts.speak(BlindUserGatewayPage.this, "Wrong username or password. Please try again. Current item: " + spokenMenu.get(currentItem).getSpokenName());
			}
			else if(progress[0]==2) {
				progressDialog.dismiss();
				tts.speak(BlindUserGatewayPage.this, "Your user is not yet activated. Please check your e-mail. Current item: " + spokenMenu.get(currentItem).getSpokenName());
			}
			else if(progress[0]==3) {
				progressDialog.dismiss();

				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
				SharedPreferences.Editor editor = preferences.edit();
				editor.putBoolean("autoLogin", true);
				editor.putString("email", emailString);
				editor.putString("password", passwordString);
				editor.putBoolean("blindUserMode", true);
				editor.commit();

				SharedPreferences savePreferences = getSharedPreferences(SharedVariables.fileName, MODE_PRIVATE);
				SharedPreferences.Editor saveEditor = savePreferences.edit();
				saveEditor.putString("userID", takenData[1]);
				saveEditor.putString("email", takenData[2]);
				saveEditor.putString("password", takenData[3]);
				saveEditor.putString("lastName", takenData[4]);
				saveEditor.putString("firstName", takenData[5]);
				saveEditor.putString("birthday", takenData[6]);
				saveEditor.commit();

				Intent intent = new Intent(BlindUserGatewayPage.this, BlindUserMainPage.class);
				startActivity(intent);

				finish();
			}
			else if(progress[0]==4) {
				progressDialog.dismiss();
				tts.speak(BlindUserGatewayPage.this, "Connection problem. Please try again. Current item: " + spokenMenu.get(currentItem).getSpokenName());
			}
		}

		protected void onPostExecute(String result) {}
	}
}
